package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.StringReader;
import java.util.LinkedHashMap;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.fragment.LogInDiaLog;
import zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager;
import zj.it.bhne.gridengineeringsurvey.myutils.config.NetConfig;

import static zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig.callService;
import static zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager.getThreadPool;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    //private static final String TAG = "LoginActivity";
    private ProgressDialog mProgressDialog;
    private EditText mUsername;
    private EditText mPassword;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //若工作完成，取消动画，初始化界面
            mProgressDialog.cancel();
        }
    };
    /**
     * 线程
     */
    private Runnable mRunnable = () -> {
        //需要耗时的工作
        initData();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };
    private boolean viewPwd = false;//设置密码是否可见
    private LogInDiaLog mDiaLog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        isLogin();
        initView();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    /**
     * 登录逻辑
     */
    private void initData() {

        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        //1.登陆接口 POST
        map.put("Username", mUsername.getText().toString());
        map.put("Password", mPassword.getText().toString());
        String result = callService("getwebuser", map);

        ////Log.e("TAG", "initData: " + result);
        if (parseXMLWithPull(result)) {
            finish();
            startActivity(new Intent(this, BottomActivity.class));
            ToastUtils.showShort("登录成功");
            SPUtils.getInstance().put("mUsername", mUsername.getText().toString());
            SPUtils.getInstance().put("mPassword", mPassword.getText().toString());
            //Log.e("TAG", "initDatassss: " + SPUtils.getInstance().getString("token"));
        } else {
            ToastUtils.showShort("登录异常");
        }
    }

    //1.TODO 用户登陆解析用Pull方式解析XML
    private Boolean parseXMLWithPull(String xmlData) {
        int res = 1;
        try {

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            //设置输入的内容
            xmlPullParser.setInput(new StringReader(xmlData));
            //获取当前解析事件，返回的是数字
            int eventType = xmlPullParser.getEventType();
            //保存内容
            String msg;
            String usersId;
            String name;

            while (eventType != (XmlPullParser.END_DOCUMENT)) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析XML
                    case XmlPullParser.START_TAG: {
                        //nextText()用于获取结点内的具体内容
                        if ("usersId".equals(nodeName)) {
                            usersId = xmlPullParser.nextText();
                            //SharedPreferencesUtils.putString(getApplicationContext(), "userId", usersId);
                            SPUtils.getInstance().put("usersId", usersId);
                        }
                        if ("msg".equals(nodeName)) {
                            msg = xmlPullParser.nextText();

                            if (msg.equals("成功")) {
                                SPUtils.getInstance().put("islogin", "1");
                                res = 0;
                            }
                        }
                        if ("token".equals(nodeName)) {
                            String token = xmlPullParser.nextText();
                            SPUtils.getInstance().put("token", token);
                        }
                        if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                            SPUtils.getInstance().put("name", name);
                        }

                        /*else if("version".equals(nodeName))
                            version = xmlPullParser.nextText();*/
                    }
                    break;
                    //结束解析
                    case XmlPullParser.END_TAG: {
                    }
                    break;
                    default:
                        break;
                }
                //下一个
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res == 0;
    }

    public void isLogin() {
        if (MyApplication.getInstances().IsLogin()) {
            finish();
            startActivity(new Intent(this, BottomActivity.class));
        }
    }

    private void initView() {
        mUsername = findViewById(R.id.ac_login_username_et);
        mPassword = findViewById(R.id.ac_login_pw_et);
        Button mLogin1 = findViewById(R.id.ac_login_button);
        mLogin1.setOnClickListener(this);
        ImageView ac_login_delete_name = findViewById(R.id.ac_login_delete_name);
        ac_login_delete_name.setOnClickListener(this);
        ImageView ac_login_view_pwd = findViewById(R.id.ac_login_view_pwd);
        ac_login_view_pwd.setOnClickListener(this);
        TextView ac_login_set_net = findViewById(R.id.ac_login_set_net);
        ac_login_set_net.setOnClickListener(this);

        String name = SPUtils.getInstance().getString("mUsername");
        String pass = SPUtils.getInstance().getString("mPassword");
        if (!name.equals("")||name!=null){
            mUsername.setText(name);
        }
        if (!pass.equals("")||pass!=null){
            mPassword.setText(pass);
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*case R.id.activity_login_go_rigest_bn:
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("Token", SPUtils.getInstance().getString("token"));
                String result = callService("verifyToken", map);
                //Log.e("reulst_ww", result);
                //startActivity(new Intent(this, RegisterActivityMy.class));
                break;*/
            case R.id.ac_login_set_net:
                showSetNetHttpDialog();
                break;
            case R.id.ac_login_delete_name:
                //清空输入的账号信息
                mUsername.setText("");
                break;
            case R.id.ac_login_view_pwd:
                if (!viewPwd) {
                    //选择状态 显示明文--设置为可见的密码
                    mPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mPassword.setSelection(mPassword.length());//但是密码显示后,文本光标会跑到开头去,重新在文本末获取一下光标
                    viewPwd = true;
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mPassword.setSelection(mPassword.length());//但是密码显示后,文本光标会跑到开头去,重新在文本末获取一下光标
                    viewPwd = false;
                }
                break;
            case R.id.ac_login_button:
                //登陆逻辑代码
                if (mUsername.getText().toString().trim().isEmpty()) {
                    Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
                } else if (mPassword.getText().toString().trim().isEmpty()) {
                    Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    SPUtils.getInstance().put("mUsername", mUsername.getText().toString());
                    KeyboardUtils.hideSoftInput(this);
                    //startActivity(new Intent(this, BottomActivity.class));
                    if (NetworkUtils.isConnected()) {
                        mProgressDialog = new ProgressDialog(this);
                        mProgressDialog.setMessage("正在登录,请稍等...");
                        mProgressDialog.setCanceledOnTouchOutside(false);
                        mProgressDialog.show();
                        ThreadManager.ThreadPool threadPool = getThreadPool();
                        threadPool.execute(mRunnable);
                    } else {
                        ToastUtils.showShort("网络无连接");
                    }
                }
                break;
        }
    }

    /**
     * 设置网络
     */
    private void showSetNetHttpDialog() {
        View viewDialog = View.inflate(this, R.layout.dialog_set_netip, null);
        viewDialog.measure(0, 0);
        int measuredHeight = viewDialog.getMeasuredHeight();
        int measuredWidth = viewDialog.getMeasuredWidth();
        mDiaLog = new LogInDiaLog(this, measuredWidth, measuredHeight, viewDialog, R.style.dialog);
        EditText IPSet = mDiaLog.findViewById(R.id.IPSet);
        EditText HTTPSet = mDiaLog.findViewById(R.id.HTTPSet);
        Button setNetConfirm = mDiaLog.findViewById(R.id.SetNet_bt_confirm);
        Button setNetCancel = mDiaLog.findViewById(R.id.SetNet_bt_cancel);
        String iptext = SPUtils.getInstance().getString("IPTEXT");
        String httptext = SPUtils.getInstance().getString("HTTPTEXT");
        IPSet.setText(iptext);
        HTTPSet.setText(httptext);
        setNetConfirm.setOnClickListener(v -> {
            String IPSetString = IPSet.getText().toString().trim();
            String HTTPSetString = HTTPSet.getText().toString().trim();
            if (!TextUtils.isEmpty(IPSetString) || !TextUtils.isEmpty(HTTPSetString)) {
                SPUtils.getInstance().put("IPTEXT", IPSetString);
                SPUtils.getInstance().put("HTTPTEXT", HTTPSetString);
                //http://192.168.32.98:8080/
                NetConfig.MAIN = "http://" + IPSetString + ":" + HTTPSetString;
                mDiaLog.dismiss();
            } else {
                ToastUtils.showShort("请填写完整");
            }
        });
        setNetCancel.setOnClickListener(v -> {
            mDiaLog.dismiss();
            NetConfig.MAIN = "http://192.168.9.21:8080";
        });
        mDiaLog.show();
    }

}
